//
//  AllCityVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2018/2/1.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "AllCityVC.h"
#import "SectionIndexView.h"
#import "SearchResultsControllerTableViewController.h"

#import "RecommndCityListCell.h"
#import "SearchCuntryHeaderView.h"

#import "CityVC.h"

@interface AllCityVC () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) NSArray * countyListArray;

@property (nonatomic, strong) SearchResultsControllerTableViewController *searchResultTVC;
@property (nonatomic, strong) SectionIndexView * indexView;
@property (nonatomic, strong) UITableView * resultTableView;
@property (nonatomic, strong) NSArray * resultArray;



@end

@implementation AllCityVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUp];
}
- (void)setUp {
    
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    
    self.searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH_CITY", nil);
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    
    searchField.font = Font(14);
    
    self.resultTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    
    self.resultTableView.delegate = self;
    self.resultTableView.dataSource = self;
    self.resultTableView.tag = 3333;

    [self.view addSubview:self.resultTableView];
    
    [self.resultTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.tableView);
    }];
    
    self.resultTableView.hidden = YES;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.tableView registerClass:[RecommndCityListCell class] forCellReuseIdentifier:@"RecommndCityListCell"];
    [self.tableView registerClass:[SearchCuntryHeaderView class] forHeaderFooterViewReuseIdentifier:@"SearchCuntryHeaderView"];
    [self.resultTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self loadDataSource];
}

- (void)loadDataSource {
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    if (![CountryManager sharedManager].onlinecountry) {
        @weakify(self);
        [NetAPIManager getOnlinecitiesWithBlock:^(NSArray *onlinecountry, NSError *error) {
            @strongify(self);
            
            [CountryManager sharedManager].onlinecountry = onlinecountry;
            [self setupData];
        }];
        
        return;
    }
    
    [self setupData];
}

- (void)setupData {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        self.countyListArray = [CountryManager sharedManager].onlinecountry;
        
        
        NSMutableArray *array = [NSMutableArray array];
        
        
        for (Country *country in self.countyListArray) {
            [array addObject:[IGUtil firstCharactor:country.smartName]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^ {
            [ActivityIndicatorView hideHUDAddedTo:self.view];
            [self.tableView reloadData];
            
            UIView *lastView = [self.view viewWithTag:1000];
            
            if (lastView) {
                [lastView removeFromSuperview];
            }
            
            _indexView = [[SectionIndexView alloc] initWithFrame:CGRectMake(kScreenWidth - 30,44, 30, kScreenHeight - kNavigationBarHeight - 88 - kTableBarHeight) sectionTitles:array];
            _indexView.delegate = self;
            _indexView.tag = 1000;
            
            [self.view insertSubview:_indexView belowSubview:self.resultTableView];
        });
    });
}

- (void)selectIndex:(NSInteger)index {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

#pragma mark - search
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    if (searchBar.text.length > 0) {
        
        searchBar.placeholder = @"";
    }
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH_CITY", nil);
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    self.resultTableView.hidden = NO;
    
    if (searchText.length > 0) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.resultArray = [[CountryManager sharedManager] getCitysMatch:searchText];
            dispatch_async(dispatch_get_main_queue(), ^ {
                [self.resultTableView reloadData];
            });
        });
    } else {
        
        searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH_CITY", nil);
        self.resultTableView.hidden = YES;
        self.indexView.hidden = NO;
        [self.tableView reloadData];
    }
}
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
#pragma makr - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView.tag == 3333) {
        
        return self.resultArray.count;
    }
    
    Country *county = self.countyListArray[section];
    
    return county.cities.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView.tag == 3333) {
        
        return  1;
    }
    
    return self.countyListArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    if (indexPath.section == 0 && self.gpsCity) {
    //
    //        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    //
    //        if (!cell) {
    //            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
    //            cell.textLabel.textColor = kSubitleColor;
    //            cell.textLabel.font = Font(14);
    //            cell.imageView.image = [UIImage imageNamed:@"position"];
    //        }
    //        cell.textLabel.text = self.gpsCity.smartName;
    //
    //        return cell;
    //    }
    //
    //    if ((self.gpsCity && self.dataSource.count != 0 && indexPath.section == 1) || (indexPath.section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
    //
    //        RecommndCityListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommndCityListCell"];
    //
    //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //        cell.delegate = self;
    //        [cell configData:self.dataSource];
    //
    //        return cell;
    //    }
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.textColor = kSubitleColor;
    cell.textLabel.font = Font(14);
    
    City * city;
    if (tableView.tag == 3333) {
        
        city = self.resultArray[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }else{
        Country * county = self.countyListArray[indexPath.section];
        city = county.cities[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.textLabel.text  = city.smartName;
    
    cell.imageView.image = [UIImage imageNamed:@"position"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    City *city;
    if (tableView.tag == 3333) {
        
        city = self.resultArray[indexPath.row];
    }else{
        
        Country * county = self.countyListArray[indexPath.section];
        city = county.cities[indexPath.row];
    }
    
    
    CityVC *cityVC = [CityVC new];
    cityVC.cid = city.cid.stringValue;
    
    [self.superVC.navigationController pushViewController:cityVC animated:YES];
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView.tag == 3333) {
        
        return nil;
    }
    
    SearchCuntryHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SearchCuntryHeaderView"];
    
    Country *county = self.countyListArray[section];
    
    headerView.cuntryNameLabel.text = county.smartName;
    
    return  headerView;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (tableView.tag == 3333) {
        
        return 0.0000001f;
    }
    
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    if ((self.gpsCity && self.dataSource.count != 0 && indexPath.section == 1) || (indexPath.section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
    //
    //        return [RecommndCityListCell getHight:self.dataSource];
    //
    //    }else {
    //
    //
    //    }
    
    return 50;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_searchBar endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)cityListSelectCity:(City *)city {
    
    [self selectCity:city];
}
#pragma mark -SearchResultsControllerTableViewController
- (void)selectCity:(City *)city {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(selectCity:)]) {
        [_delegate selectCity:city];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


